import { login, logout, getInfo } from '@/api/login' // API 请求方法
import { getToken, setToken, removeToken } from '@/utils/auth' // Token 操作工具
import { isHttp, isEmpty } from "@/utils/validate" // 路径匹配函数
import defAva from '@/assets/images/profile.png' // 默认头像
import { defineStore } from 'pinia';

const useUserStore = defineStore(  //defineStore创建一个名为user的对象来管理状态，行为（登录，获取用户信息，登出）
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      username: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        return new Promise((resolve, reject) => {
          login(username, password, code).then(res => {
            console.log(res)
            setToken(res.data)
            this.token = res.data
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },

      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo(this.id).then(res => {
            const user = res.data
            console.log(user)
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
